<!-- created by chengfei 2023/4/12 -->
<!-- 组件：列表设计-列头设置 -->
<template>
    <div>
        <div class="table-containers">
            <div class="header-toolbar">
                <!-- 选项：主键字段和显示字段显隐 -->
                <a-form-model layout="inline" style="display: flex">
                    <a-form-model-item :label="i18n('idField','主键字段')">
                        <a-select v-model="idField" :options="fieldDataAll" size="small" placeholder="请选择主键字段" style="width: 300px" />
                    </a-form-model-item>
                    <a-form-model-item :label="i18n('isFieldShow','显示字段显隐')">
                        <a-switch v-model="isFieldShow" size="small" />
                    </a-form-model-item>
                </a-form-model>
            </div>
            <!-- 按钮组：表单操作按钮 -->
            <div class="btn-box">
                <a-space style="margin-bottom: 10px">
                    <a-button type="primary" size="small" @click="reloadColumns">{{i18n('reloadColumns','重新加载表头')}}</a-button>
                    <a-button size="small" @click="addColumn">{{i18n('addColumn','新增行')}}</a-button>
                    <a-button size="small" @click="delColumn">{{i18n('delColumn','删除行')}}</a-button>
                    <a-button size="small" @click="moveUp">{{i18n('moveUp','向上')}}</a-button>
                    <a-button size="small" @click="moveDown">{{i18n('moveDown','向下')}}</a-button>
                    <a-button size="small" @click="mainHeaderRow">{{i18n('mainHeaderRow','上升一级')}}</a-button>
                    <a-button size="small" @click="subHeaderRow">{{i18n('subHeaderRow','下降一级')}}</a-button>
                    <a-button size="small" @click="expand">{{i18n('expand','展开')}}</a-button>
                    <a-button size="small" @click="collapse">{{i18n('collapse','收起')}}</a-button>
                </a-space>
            </div>
            <rx-grid
                ref="table"
                :columns="columns"
                :data-source="fieldList"
                :allow-row-select="true"
                :bordered="true"
                :multiSelect="true"
                :show-page="false"
                id-field="idx_"
                style="min-height: 300px"
            >
                <!-- 插槽：宽度字段表头 -->
                <template #customTitle>
                    {{i18n('width','宽度')}}
                    <a-tooltip>
                        <template #title>
                            {{i18n('warning','注意：')}}
                        </template>
                        <a-icon type="question-circle-o" />
                    </a-tooltip>
                </template>
                <!-- 插槽：字段名称 -->
                <template #header="{ record }">
                    <a-input v-model="record.header" style="width: 100%" />
                </template>

                <!-- 插槽：字段Key -->
                <template #field="{ record }">
                    <a-select
                        v-model="record.field"
                        :options="fieldDataAll"
                        style="width: 100%"
                        @change="changeFieldName($event, record, 'header')"
                    />
                </template>

                <!-- 插槽：宽度 -->
                <template #width="{ record }">
                    <a-input-number v-model="record.width" :min="5" :max="1200" style="width: 100%" />
                </template>

                <!-- 插槽：文本位置 -->
                <template #headerAlign="{ record }">
                    <a-select v-model="record.headerAlign" style="width: 100%">
                        <a-select-option value="center">{{i18n('center','居中')}}</a-select-option>
                        <a-select-option value="left">{{i18n('left','居左')}}</a-select-option>
                        <a-select-option value="right">{{i18n('right','居右')}}</a-select-option>
                    </a-select>
                </template>

                <!-- 插槽：锁定位置 -->
                <template #fixed="{ record }">
                    <a-select v-model="record.fixed" style="width: 100%">
                        <a-select-option value="false">&nbsp;</a-select-option>
                        <a-select-option value="left">{{i18n('fixedLeft','固定左')}}</a-select-option>
                        <a-select-option value="right">{{i18n('fixedRight','固定右')}}</a-select-option>
                    </a-select>
                </template>

                <!-- 插槽： 列头渲染-->
                <template #customTitleRender="{ text, record, index }">
                    <a-button @click.stop="cellHeaderConfig(record)">
                        {{i18n('render','渲染')}}
                    </a-button>
                    <span v-if="record.isSetedRender" class="is-seted">
                        <i class="iconfont iconsuccess_fill is-seted" />
                        {{i18n('hasSet','已配')}}
                    </span>
                    <a-icon
                        v-if="record.isSetedRender"
                        type="delete"
                        style="margin-left: 10px"
                        @click.stop="clearRenderSetting(record)"
                    />
                </template>
            </rx-grid>
        </div>
    </div>
</template>

<script>
import { RxGrid, RxInputButton, Util, GridMixin, BaseForm } from "@lowcode/jpaas-common-lib"
import FormBoListCellHeader from '@/views/modules/form/core/FormBoListCellHeader'

export default {
    name: 'ColumnConf',
    // 引入表格新增/删除/移动行等操作
    mixins: [GridMixin, BaseForm],
    components: {
        RxGrid,
        RxInputButton,
    },
    props: {
        defaultValue: { type: Object, default: () => {} },
        fieldDataAll: { type: Array, default: () => []}
    },
    data() {
        return {
            idField: '',
            isFieldShow: true,
            // 表格
            // 表格：表头
            columns: [
                { title: this.i18n('form.header','字段名称'), dataIndex: 'header', scopedSlots: { customRender: 'header' }, width: 120 },
                { title: this.i18n('form.field','字段Key'), dataIndex: 'field', scopedSlots: { customRender: 'field' }, width: 120 },
                {
                    title: this.i18n('form.allowSort','可排序'),
                    dataIndex: 'allowSort',
                    type: 'checkboxColumn',
                    scopedSlots: { customRender: 'allowSort' },
                    width: 80,
                    align: 'center',
                },
                {
                    slots: { title: 'customTitle' },
                    dataIndex: 'width',
                    scopedSlots: { customRender: 'width' },
                    width: 80,
                },
                {
                    title: this.i18n('form.headerAlign','文本位置'),
                    dataIndex: 'headerAlign',
                    scopedSlots: { customRender: 'headerAlign' },
                    width: 80,
                },
                {
                    title: this.i18n('form.fixed','锁定位置'),
                    dataIndex: 'fixed',
                    scopedSlots: { customRender: 'fixed' },
                    width: 100,
                },
                {
                    title: this.i18n('form.customTitleRender','列头渲染'),
                    dataIndex: 'customTitleRender',
                    scopedSlots: { customRender: 'customTitleRender' },
                    width: 100,
                }
            ],
            headerFields: [],
            // 表格：数据
            fieldList: []
        }
    },
    mounted() {
        const { idField, isFieldShow, columnList } = this.defaultValue
        this.idField = idField || ''
        this.fieldDataAll.forEach(item=>{
            if(!this.idField && item.isPk==1){
                this.idField=item.value;
            }
        })
        this.isFieldShow = isFieldShow === 'YES' || isFieldShow === undefined
        this.fieldList = columnList ? [...columnList] : this.fieldDataAll.filter(item=>{
            return !["rx-commonfield","rx-ref"].includes(item.control);
        }).map(item=>{
            return {
                header: item.label,
                allowSort: false,
                width: 100,
                field: item.value,
                fieldName: item.fieldName,
                control: '',
                headerAlign: 'center',
                fixed: '',
                isSetedRender:false
            }
        })
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"formCodegenBusiness.edit2.columnConfLang",key);
        },
        // tool
        // 重新加载表头
        reloadColumns() {
            var self=this;
            this.fieldDataAll.filter(item=>{
                return !["rx-commonfield","rx-ref"].includes(item.control);
            }).forEach(item=>{
                var flag=true;
                //有相同的则只替换名称
                for (let i = 0; i < self.fieldList.length; i++) {
                    if(item.value==self.fieldList[i].field){
                        self.fieldList[i].header=item.label;
                        flag=false;
                        break;
                    }
                }
                if(flag){
                    self.fieldList.push({
                        header: item.label,
                        allowSort: false,
                        width: 100,
                        field: item.value,
                        fieldName:item.fieldName,
                        control: '',
                        headerAlign: 'center',
                        fixed: '',
                        isSetedRender:false
                    });
                }
            })
        },
        // 新增行
        addColumn() {
            const newCol = {
                header: '',
                allowSort: false,
                width: 100,
                field: '',
                control: '',
                headerAlign: '',
                fixed: '',
                isSetedRender:false
            }
            this.$refs.table.addRow(newCol)
        },
        // 删除行
        delColumn() {
            const table = this.$refs.table
            table.removeRows()
            table.selectedRowKeys = []
            table.selectedRows = []
            this.$forceUpdate()
        },
        // 向上
        moveUp() {
            this.$refs.table.moveUp()
        },
        // 向下
        moveDown() {
            this.$refs.table.moveDown()
        },
        // 上升一级
        mainHeaderRow() {
            this.$refs.table.toMain()
        },
        // 下降一级
        subHeaderRow() {
            this.$refs.table.toSub()
        },
        // 展开
        expand() {
            this.$refs.table.expand()
        },
        // 收起
        collapse() {
            this.$refs.table.collapse()
        },
        // 列头渲染
        cellHeaderConfig(record) {
            const table = this.$refs.table
            const conf = {
                component: FormBoListCellHeader,
                title: this.i18n('cellHeaderRender','列头渲染配置'),
                curVm: this,
                data: { render: record },
                widthHeight: ['800px', '600px'],
                shade: true,
            }

            Util.open(conf, function (action) {
                if (action != 'ok') {
                    return
                }
                const data = this.getData()
                table.updateRow(record, { customTitle: data.customTitle,isSetedRender:true })
            })
        },
        clearRenderSetting(record){
            this.$confirm({
                title: this.$ti18("rxMsa.tipsInfo","提示信息"),
                content: this.i18n('tipsInfo','确认删除配置吗?'),
                onOk() {
                    record.customTitle="";
                    record.isSetedRender=false;
                },
                zIndex:10000,
                onCancel() {},
                okText: this.$ti18('rxForm.okBtn','确定'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
            });

        },

        // 表格：可排序字段选中/取消选择的回调
        sortableChecked(record) {
            if (record.sortable === 1) {
                record.sortable = 0
            } else {
                record.sortable = 1
            }
        },
        changeFieldName(value, record, header) {
            for (let i = 0; i < this.fieldDataAll.length; i++) {
                if (this.fieldDataAll[i].value == value) {
                    record.fieldName=this.fieldDataAll[i].fieldName
                    if (header) {
                        record[header] = this.fieldDataAll[i].label
                    }
                    break
                }
            }
        },
        collectData() {
            let result={success:true};
            if(!this.idField){
                result.success=false;
                result.message="主键字段不能为空！";
                return result;
            }

            const columns = this.$refs.table.getData()
            // 去除空行
            var newColumns = []
            columns.forEach((elem) => {
                if (elem.header && elem.field) {
                    newColumns.push(elem)
                }
            })
            const config = {
                columnList: newColumns,
                idField: this.idField,
                isFieldShow: this.isFieldShow ? 'YES' : 'NO',
            }
            result.data=config;
            return result;
        },
    },
}
</script>

<style scoped>
.is-seted {
    color: #70b90b;
    margin-left: 5px;
}
</style>
